package com.qianchang.microfinance.view.credit.data;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.model.IPickerViewData;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.StringUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.utils.ViewUtils;
import com.dm.library.widgets.ClearEditText;
import com.dm.library.widgets.OneLineLinearLayout;
import com.dm.library.widgets.element.DButton;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.BankBean;
import com.qianchang.microfinance.bean.FindUserBasicInfoBean;
import com.qianchang.microfinance.bean.OpenAccDataBean;
import com.qianchang.microfinance.bean.PageBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.banktonuber.Bankinfo;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.dialog.CommonDialog;
import com.qianchang.microfinance.view.hsbindbank.HSAuthorizedActivity;
import com.qianchang.microfinance.view.hsbindbank.HSBindBankCardActivity;
import com.qianchang.microfinance.view.hsbindbank.HSUnBindBankCardActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述:
 * 修 改 人: zhoulai
 * 修改时间: 2017/8/12 10:50
 */


public class BindBankCardActivity extends BaseActivity {

    @BindView(R.id.cardholder_name_ll)
    OneLineLinearLayout cardholderNameLl;
    @BindView(R.id.user_id_card_ll)
    OneLineLinearLayout userIdCardLl;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.ll_select_bank_name)
    LinearLayout llSelectBankName;
    @BindView(R.id.bank_card_no_tv)
    ClearEditText bankCardNoEt;
    @BindView(R.id.bank_pre_phone_tv)
    EditText bankPrePhoneEt;
    @BindView(R.id.input_verify_code_et)
    ClearEditText inputVerifyCodeEt;
    @BindView(R.id.get_verify_code_tv)
    DTextView getVerifyCodeTv;
    @BindView(R.id.ll_verify_code)
    LinearLayout llVerifyCode;
    @BindView(R.id.v_bottom_line)
    View vBottomLine;
    //    @BindView(R.id.ck_protocol)
//    CheckBox ckProtocol;
//    @BindView(R.id.tv_protocol)
//    DTextView tvProtocol;
//    @BindView(R.id.ll_agreement)
//    LinearLayout llAgreement;
    @BindView(R.id.commit_tv)
    DButton commitTv;
    @BindView(R.id.ll_add_bank_card)
    LinearLayout llAddBankCard;
    //    @BindView(R.id.user_status_tv)
//    DTextView userStatusTv;
//    @BindView(R.id.action_tv)
//    DTextView actionTv;
//    @BindView(R.id.ll_no_auth)
//    LinearLayout llNoAuth;
    @BindView(R.id.tv_back)
    DTextView tvBack;
    @BindView(R.id.activity_add_bank_card)
    LinearLayout activityAddBankCard;

    private FindUserBasicInfoBean basicInfoBean;
    private boolean isDetail = false;//是验证银行卡  还是新增（绑定银行卡）
    private List<BankBean> bankList = new ArrayList<>();
    private BankBean bankBean;//所选银行
    private String accountName;//用户名称 要传过来！~！
    private String idCard;//身份证号码 要传过来！~！
    private String REQ_SN;//下一步接口返回值
    private CountDownTimer phoneDownTimer;
    private String cardNo;
    private String phone;
    private boolean isConfirmlGoing = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_bank_card);
        ButterKnife.bind(this);
        initView();
        initData();
    }


    private void initAddBankCardView() {//新增

        commitTv.setText(getString(R.string.next_step));
        llVerifyCode.setVisibility(View.GONE);
        bankCardNoEt.setTextContent(cardNo);
        bankPrePhoneEt.setText(phone);

        llSelectBankName.setEnabled(true);
        bankCardNoEt.setEnabled(true);
        bankPrePhoneEt.setEnabled(true);
        bankCardNoEt.setFocusable(true);
        bankPrePhoneEt.setFocusable(true);

        isDetail = false;

        if (null != phoneDownTimer) {
            phoneDownTimer.cancel();
        }
        setTitleName("绑定银行卡");
    }

    private void initIdentifyBankCardView() {//验证（详情
        llVerifyCode.setVisibility(View.VISIBLE);
        commitTv.setText(getString(R.string.commit));
        bankCardNoEt.setText(ViewUtils.formatBankCard(bankCardNoEt.getText().toString().trim()));
        bankPrePhoneEt.setText(ViewUtils.formatPhone(bankPrePhoneEt.getText().toString().trim()));

        llSelectBankName.setEnabled(false);
        bankCardNoEt.setEnabled(false);
        bankPrePhoneEt.setEnabled(false);
        bankCardNoEt.setFocusable(false);
        bankPrePhoneEt.setFocusable(false);

        setTitleName("银行卡验证");
    }

    private boolean isConfirml = false;

    @Override
    protected void initView() {
        super.initView();
        initAddBankCardView();
        setTitleName("绑定银行卡");
//        tvProtocol.setText("《委托扣款授权书》");
        Bundle bundle = getBundle();
        if (null != bundle) {
            isConfirml = bundle.getBoolean("isConfirml",false);
            basicInfoBean = (FindUserBasicInfoBean) bundle.getSerializable(ConstantAppInfo.BASIC_INFO_BEAN);
            if (basicInfoBean == null) {
                basicInfoBean = new FindUserBasicInfoBean();
            } else {
                cardholderNameLl.setRightContent(ViewUtils.formatRealName(basicInfoBean.getRealName()));
                userIdCardLl.setRightContent(ViewUtils.formatIdCard(basicInfoBean.getIdCard()));
                if (0 == basicInfoBean.getIsBankCardBind()) {               //isBankCardBind	是否添加银行卡绑定，0：是、1：否
                    isDetail = true;
                }
            }
        }

        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isDetail) {
                    initAddBankCardView();
                } else {
                    finish();
                }
            }
        });


        bankCardNoEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int before, int count) {
               int huoqu = bankCardNoEt.getText().toString().length();
                if (huoqu >= 6) {
                    String huoqucc = bankCardNoEt.getText().toString();
                    String name = Bankinfo.getNameOfBank(huoqucc);// 获取银行卡的信息
                    tvBankName.setText(name);
                } else {
                    tvBankName.setText(null);
                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

               /* int huoqu = bankCardNoEt.getText().toString().length();
                if (huoqu >= 6) {
                    String huoqucc = bankCardNoEt.getText().toString();
                    String name = Bankinfo.getNameOfBank(huoqucc);// 获取银行卡的信息
                    tvBankName.setText(name);
                } else {
                    tvBankName.setText(null);
                }*/
            }
        });


//        ckProtocol.setText("点击下一步即视为同意");
    }

    @Override
    protected void initData() {
        super.initData();
        //getBankList();

    }

    private void getBankList() {
        show();
        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.FIND_BANK_LIST, params, new RequestCallBack<PageBean<BankBean>>() {

            @Override
            public void onSuccess(JsonResult<PageBean<BankBean>> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    if (response.getObject() != null && response.getObject().getList() != null && !response.getObject().getList().isEmpty()) {
                        bankList.clear();
                        bankList.addAll(response.getObject().getList());
                    } else {
                        ToastUtil.getInstant().show(BindBankCardActivity.this, getString(R.string.msg_get_bank_list_fail));
                    }
                } else {
                    ToastUtil.getInstant().show(BindBankCardActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(BindBankCardActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    @OnClick({R.id.ll_select_bank_name, R.id.commit_tv, R.id.get_verify_code_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_select_bank_name:
                CommonDialog.Builder builder = CommonDialog.init()
                        .setOnItemSelectListener(new CommonDialog.OnItemSelectListener() {
                            @Override
                            public void onItemSelect(IPickerViewData iPickerViewData, int position, int flag) {
                                bankBean = (BankBean) iPickerViewData;
                                if (bankBean == null) {
                                    ToastUtil.getInstant().show(BindBankCardActivity.this, getString(R.string.data_error));
                                    return;
                                }
                                tvBankName.setText(bankBean.getBankName());
                            }
                        })
                        .setContext(this);
                builder.setData(bankList)
                        .setFlag(0)
                        .setTitle(getString(R.string.msg_select_bank_name));
                builder.build().showPickerView();

                break;
            case R.id.commit_tv:

                //以下为新增自己功能逻辑2018.1.18
                int openAccount = basicInfoBean.getIsOpenAccount();   //是否新网开户授权0：是，1：否
                if(openAccount == 1){
                    hsSubmit();
                }else{
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isConfirml",isConfirml);
                    startActivity(HSBindBankCardActivity.class,bundle,true);            //如果授权过新网银行绑定银行卡的授权，直接跳转至绑定银行卡页面
                }

                //以下占时注释迪蒙代码 2018.1.18
//                if (isDetail) {
//                    submit();    //验证提交
//                } else {
//                    nextStep();  //下一步
//                }
                break;
            case R.id.get_verify_code_tv:
                sendIdentifyCode();
                break;
//            case R.id.tv_protocol:
//                Bundle bundle = new Bundle();
//                bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, "8");
//                startActivity(AgreementActivity.class, bundle);
//                break;
        }
    }

    private void sendIdentifyCode() {
        show();
        HttpParams params = new HttpParams();
        params.put("REQ_SN", REQ_SN);
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.SEND_BANK_INDENTIFY_CODE, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    showRemainTime();
                } else {
                    ToastUtil.getInstant().show(BindBankCardActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(BindBankCardActivity.this, msg);
                dismiss();
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    /**
     * 2018.1.9鸿盛科技新增绑定银行卡
     */

    //第一次新网银行授权
    private void hsSubmit(){

        cardNo = bankCardNoEt.getText().toString().trim();
        phone = bankPrePhoneEt.getText().toString().trim();

        if (!FormatUtil.checkBankCard(cardNo)) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_bank_card_not_ok));
            return;
        }
        if (!FormatUtil.isValidPhone(phone, null)) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_phone_input_error));
            return;
        }
//        if (StringUtils.isEmptyOrNull(tvBankName.getText().toString().trim())) {
//            ToastUtil.getInstant().show(this, getString(R.string.msg_select_bank_name));
//            return;
//        }

        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();
        HttpParams params = new HttpParams();
        params.put("userId", usid);
        params.put("bankCard", cardNo);
        params.put("bankCardPhone", phone);
        show();

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.OPEN_ACCOUNT, params, new RequestCallBack<OpenAccDataBean>() {


            @Override
            public void onSuccess(JsonResult<OpenAccDataBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    OpenAccDataBean openAccBean = response.getObject();
                    if (openAccBean != null) {
                        String mesg = openAccBean.getMessage();
                        if(null != mesg){
                            if("账户授权成功".equals(mesg)) {
                                Bundle bundle = new Bundle();
                                bundle.putSerializable(ConstantAppInfo.OPEN_ACCOUNT_BEAN, openAccBean);
                                bundle.putBoolean("isConfirml", isConfirmlGoing);
                                startActivity(HSAuthorizedActivity.class, bundle, true);
                            }else {
                                if(basicInfoBean.getIsBankCardBind() != 0){
                                    Bundle bundle = new Bundle();
                                    bundle.putBoolean("isConfirml",isConfirmlGoing);
                                    startActivity(HSBindBankCardActivity.class,bundle,true);
                                }
                                ToastUtil.getInstant().show(BindBankCardActivity.this, mesg);
                                DMLog.e("是接口 == OPEN_ACCOUNT"+mesg);
                            }
                        }else{
                            ToastUtil.getInstant().show(BindBankCardActivity.this, "数据异常");
                            DMLog.e("数据异常  是接口 == OPEN_ACCOUNT");
                        }
                       /* if(mesg != null && mesg.equals("账户授权成功")){
                            if(basicInfoBean.getIsBankCardBind() != 0){
                                Bundle bundle = new Bundle();
                                bundle.putBoolean("isConfirml",isConfirmlGoing);
                                startActivity(HSBindBankCardActivity.class,bundle,true);
                            }
                        }else if(mesg == null || !(mesg.equals("该帐户已授权"))){
                            ToastUtil.getInstant().show(BindBankCardActivity.this, "数据异常");
                            DMLog.e("数据异常  是接口 == OPEN_ACCOUNT");
                        } else {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(ConstantAppInfo.OPEN_ACCOUNT_BEAN, openAccBean);
                            bundle.putBoolean("isConfirml",isConfirmlGoing);
                            startActivity(HSAuthorizedActivity.class, bundle,true);
                        }*/
                    } else {
                        ToastUtil.getInstant().show(BindBankCardActivity.this, response.getDescription());
                    }
                } else {
                    ToastUtil.getInstant().show(BindBankCardActivity.this, response.getDescription());
                }

            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(BindBankCardActivity.this, msg);
                dismiss();
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }


    private void submit() {
        String verifyCode = inputVerifyCodeEt.getText().toString();
        if (TextUtils.isEmpty(verifyCode)) {
            ToastUtil.getInstant().show(BindBankCardActivity.this, getString(R.string.please_enter_verification_code));
            return;
        }
        show();
        HttpParams params = new HttpParams();

//        1	userId	Y	用户ID
        params.put("REQ_SN", REQ_SN);//	支付批次号
        params.put("VERCODE", verifyCode);//验证码
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.TO_SUBMIT_BANK, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    finish();
                } else {
                    ToastUtil.getInstant().show(BindBankCardActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(BindBankCardActivity.this, msg);
                dismiss();
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void nextStep() {
        cardNo = bankCardNoEt.getText().toString().trim();
        phone = bankPrePhoneEt.getText().toString().trim();

        if (!FormatUtil.checkBankCard(cardNo)) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_bank_card_not_ok));
            return;
        }
        if (!FormatUtil.isValidPhone(phone, null)) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_phone_input_error));
            return;
        }
        if (StringUtils.isEmptyOrNull(tvBankName.getText().toString().trim())) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_select_bank_name));
            return;
        }

        if (bankBean == null) {
            ToastUtil.getInstant().show(BindBankCardActivity.this, getString(R.string.msg_get_bank_list_fail));
            return;
        }

        if (!StringUtils.isEmptyOrNull(basicInfoBean.getRealName())) {
            accountName = basicInfoBean.getRealName();//首页测测额度进来
            idCard = basicInfoBean.getIdCard();
        }
        show();
        HttpParams params = new HttpParams();
        params.put("bankCode", bankBean.getBankCode());//银行代码
        params.put("accountType", "00");//账号类型  00银行卡，01存折，02信用卡。不填默认为银行卡00。
        params.put("cardNo", cardNo);//银行卡账号
        params.put("accountName", accountName);//银行卡或存折上的所有人姓名 账号名    要传过来！~！
        params.put("accountProp", "0");//账号属性0私人，1公司。不填时，默认为私人0
        params.put("idType", "0");//	开户证件类型  0：身份证,1: 户口簿，2：护照,3.军官证,4.士兵证，5. 港澳居民来往内地通行证,6. 台湾同胞来往内地通行证,7. 临时身份证,8. 外国人居留证,9. 警官证, X.其他证件
        params.put("idCard", idCard);//身份证件号  要传过来！~！
        params.put("phone", phone);//	电话号码
        params.put("bankId", bankBean.getId());//银行ID*/

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.INSERT_BANK_CARD, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    REQ_SN = response.getObject();
                    isDetail = true;
                    initIdentifyBankCardView();
                    sendIdentifyCode(); //下一步成功之后直接发送短信
                } else {
                    ToastUtil.getInstant().show(BindBankCardActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(BindBankCardActivity.this, msg);
                dismiss();
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    //显示获取手机验证码倒计时
    private void showRemainTime() {
        getVerifyCodeTv.setEnabled(false);
        phoneDownTimer = new CountDownTimer(ConstantAppInfo.DEFAULT_TIME, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int temp = (int) (millisUntilFinished / 1000);
                getVerifyCodeTv.setText(temp + "S");
                getVerifyCodeTv.setEnabled(false);
            }

            @Override
            public void onFinish() {
                getVerifyCodeTv.setText(getString(R.string.btn_get_verify_code));
                getVerifyCodeTv.setEnabled(true);
            }
        }.start();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //按两次返回退出应用程序
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isDetail) {
                initAddBankCardView();
            } else {
                super.onBackPressed();
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
